package com.mrent.service;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.EntityTransaction;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import com.mrent.entity.CartGoods;

@Component
public class CartGoodsServiceImpl implements CartGoodsService{
	
	/**
	 * 保存购物车商品.
	 * 
	 * @param cartGoods
	 */
	public void saveCartGoods(CartGoods cartGoods){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try{
			trans.begin();
			em.persist(cartGoods);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			trans.commit();
		}
	}
	
	
	
	/**
	 * 更新购物车对象.
	 * 
	 * @param cartGoods
	 */
	public void updateCartGoods(CartGoods cartGoods){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try{
			trans.begin();
			em.merge(cartGoods);
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			trans.commit();
		}
	}
	
	/**
	 * 删除购物车商品.
	 * 
	 * @param cartGoods
	 */
	public void removeCartGoods(Long  cartId){
		EntityManager em = EMF.getEM();
		EntityTransaction trans = em.getTransaction();
		try{
			trans.begin();
			CartGoods cartGoods = em.find(CartGoods.class, cartId);
			if(cartGoods != null){
				em.remove(cartGoods);
			}
		}catch(Exception e){
			e.printStackTrace();
		}finally{
			trans.commit();
		}
	}
	
	/**
	 * 根据session id 查找.
	 * 
	 * 
	 * @param sessionId
	 * @return
	 */
	public List<CartGoods> findBySession(String sessionId){
		
		EntityManager em = EMF.getEM();
		String jql = "select from CartGoods cg where cg.sessionId =:sessionId";
		Query query = em.createQuery(jql);
		query.setParameter("sessionId", sessionId);
		return query.getResultList();		
	}
	
	/**
	 * 根据session,goodsNo获取购物车商品对象.
	 * 
	 * @param sessionId
	 * @param goodsNo
	 * @return
	 */
	public CartGoods getBySessionGoodsNo(String sessionId,String goodsNo){
		
		EntityManager em = EMF.getEM();
		String jql = "select from CartGoods cg where cg.sessionId =:sessionId and cg.goodsNo=:goodsNo";
		Query query = em.createQuery(jql);
		query.setParameter("sessionId", sessionId);
		query.setParameter("goodsNo", goodsNo);
		List<CartGoods> list = query.getResultList();
		if(list.size() > 0){
			return list.get(0);
		}else{
			return null;
		}
	}

}
